﻿using System;
using System.Linq;
using Microsoft.Extensions.Logging;
using NLog;
using SqlSugar;

namespace Auth.SqlSugar
{
    public class DbInstance
    {
        /// <summary>
        /// 数据库链接字符串
        /// </summary>
        public static string DB_ConnectionString { get; set; }
        public static string Redis_ConnectionString { get; set; }
        static  Logger Logger = LogManager.GetCurrentClassLogger();
        public DbInstance()
        {
        }

        /// <summary>
        /// 获取Sugar客户端实例对象
        /// </summary>
        /// <returns>SqlSugarClient</returns>
        public static SqlSugarClient GetInstance()
        {
            ConfigureExternalServices _configureExternalServices = new ConfigureExternalServices();

            //检测是否有redis连接字符串，没有不启用二级缓存
            if (!string.IsNullOrEmpty(Redis_ConnectionString))
            {
                RedisCache.UseCache = true;
                _configureExternalServices.DataInfoCacheService = new RedisCache(Redis_ConnectionString);
            }
            

            //ICacheService myCache = new RedisCache(Redis_ConnectionString);
            SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = DB_ConnectionString,
                DbType = DbType.MySql,
                ConfigureExternalServices = _configureExternalServices
            });

            db.Ado.IsEnableLogEvent = true;
            db.Ado.LogEventStarting = (sql, pars) =>
            {
                Logger.Debug(sql);
               
                Console.WriteLine(sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                Console.WriteLine();
            };
            return db;
        }
    }
}